import * as THREE from "three";
import camera from '../camera';

export default class AlarmSprite {
    constructor(type = "火警", position = { x: 5.9, z: -1.5 }, color = 0xffffff) {
        const textureLoader = new THREE.TextureLoader();
        const typeObject = {
            电力: "./textures/tag/e.png",
            火警: "./textures/tag/fire.png",
            治安: "./textures/tag/jingcha.png"
        };

        const map = textureLoader.load(typeObject[type]);

        this.material = new THREE.SpriteMaterial({
            map: map,
            color: color,
            blending: THREE.AdditiveBlending,
            transparent: true,
            depthTest: false
        });

        // 精灵是一个总是面朝着摄像机的平面，通常含有使用一个半透明的纹理。
        this.mesh = new THREE.Sprite(this.material);

        //设置位置
        this.mesh.position.set(position.x, 3, position.z);
        // this.mesh.scale.set(1.5, 1.5, 1.5);

        // ---封装点击事件---
        this.fns = [];

        // 创建射线
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2();

        //点击事件监听
        window.addEventListener("click", (event) => {
            this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            this.mouse.y = -((event.clientY / window.innerHeight) * 2 - 1);
            // 判断是否相交
            this.raycaster.setFromCamera(this.mouse, camera);
            const intersect = this.raycaster.intersectObject(this.mesh);
            if (intersect.length > 0) {
                event.alarm = this;//传递属性
                this.fns.forEach((fn) => {
                    fn(event);
                })
            }
        });

        // ---封装点击事件---
    }
    onClick(fn) {
        this.fns.push(fn)
    }
    remove() {
        this.mesh.remove();
        this.mesh.removeFromParent();
        this.mesh.geometry.dispose();
        this.mesh.material.dispose();
    }
}